package com.lmy.androidcustomview.touch

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.lmy.androidcustomview.R
import com.lmy.androidcustomview.dp

/**
 * @author
 * @功能:多点触摸的View 触摸拖拽图片的位置
 * 协作形 或者配合形
 * @Creat 2/14/21 1:44 PM
 * @Compony 465008238@qq.com
 */

class MultiTouchView3(context: Context, attrs: AttributeSet) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val bitmap = getAvatar(200.dp.toInt())

    //图像的初始偏移
    private var originalOffsetX = 0f
    private var originalOffsetY = 0f

    //绘制的时候真正的偏移量
    private var offsetx = 0f
    private var offsety = 0f

    //记录ACTION_DOWN事件按下的位置信息
    private var downx = 0f
    private var downy = 0f

    override fun draw(canvas: Canvas) {
        super.draw(canvas)
        canvas.drawBitmap(bitmap, offsetx, offsety, paint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        //计算多点的焦点
        val focusX: Float
        val focusY: Float
        var pointerCount = event.pointerCount
        var sumx = 0f
        var sumy = 0f
        //如果事件为ACTION_POINTER_UP 此时计算焦点需要去除最后一个手指
        val isPointUp = event.actionMasked == MotionEvent.ACTION_POINTER_UP
        for (i in 0 until pointerCount) {
            if (!(isPointUp && i == event.actionIndex)) {
                sumx += event.getX(i)
                sumy += event.getY(i)
            }
        }
        if (isPointUp) {
            pointerCount--
        }
        focusX = sumx / pointerCount
        focusY = sumy / pointerCount
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_POINTER_UP -> {
                //设置初始偏移量 每次DOWN事件时会更新初始偏移量
                originalOffsetX = offsetx
                originalOffsetY = offsety
                //把当前按下的点设置为多点的焦点
                downx = focusX
                downy = focusY
            }

            MotionEvent.ACTION_MOVE -> {
                //真正的偏移量=当前移动的位置-按下位置+初始偏移量
                offsetx =
                    focusX - downx + originalOffsetX
                offsety =
                    focusY - downy + originalOffsetY
                invalidate()
            }
        }
        return true
    }

    /**
     * 限制图片的大小
     */
    private fun getAvatar(width: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(
            resources,
            R.drawable.ic_head, options
        )
        options.inJustDecodeBounds = false
        options.inDensity = options.outWidth
        options.inTargetDensity = width
        return BitmapFactory.decodeResource(
            resources,
            R.drawable.ic_head, options
        )
    }
}

